#pragma once
#include <QObject>
#include <QVector>
#include <QSet>
#include <QPoint>

enum class Color : qint8 { Empty, Black, White };

// 游戏模式枚举
enum class GameMode { Local, AI };

class GoLogic : public QObject {
    Q_OBJECT
    Q_PROPERTY(bool isBlackTurn READ isBlackTurn NOTIFY turnChanged)
    Q_PROPERTY(int gameMode READ gameMode WRITE setGameMode NOTIFY gameModeChanged)
    
public:
    explicit GoLogic(int boardSize, QObject* parent = nullptr);

    Q_INVOKABLE bool  playStone(int r, int c);
    Q_INVOKABLE bool  playStone(int r, int c, bool black); // 保留旧接口以保持向后兼容
    Q_INVOKABLE void  undo();
    Q_INVOKABLE void  reset();
    // 形势判断：返回"形势：黑领先X目"/"形势：白领先X目"或"形势：双方持平"
    Q_INVOKABLE QString score() const;
    // 形势差：黑方-白方的目数差(正=黑领先，负=白领先)
    Q_INVOKABLE int scoreDelta() const;
    // 结束点目：返回最终获胜方信息，考虑贴目规则
    Q_INVOKABLE QString finalScore() const;
    Q_INVOKABLE bool  isBlackTurn() const { return m_isBlackTurn; } // 新增方法
    Q_INVOKABLE int   gameMode() const { return static_cast<int>(m_gameMode); }
    Q_INVOKABLE void  setGameMode(int mode) { 
        if (m_gameMode != static_cast<GameMode>(mode)) {
            m_gameMode = static_cast<GameMode>(mode);
            emit gameModeChanged();
        }
    }

    QVector<Color> boardData() const { return m_board; }
    int size() const { return m_size; }

signals:
    void boardChanged();
    void capturedChanged(int b, int w);
    void turnChanged(); // 新增信号
    void gameModeChanged(); // 游戏模式变更信号

private:
    bool inBounds(int r, int c) const {
        return r >= 0 && r < m_size && c >= 0 && c < m_size;
    }
    int index(int r, int c) const { return r * m_size + c; }
    bool hasLiberty(int r, int c, Color col, QSet<int>& vis) const;
    void removeGroup(int r, int c, Color col);
    void switchTurn(); // 新增方法
    bool playStone(int r, int c, bool black, bool doSwitchTurn); // 内部重载版本

    int m_size;
    QVector<Color> m_board;
    QVector<QVector<Color>> m_history;
    int m_blackCaps = 0, m_whiteCaps = 0;
    QPoint m_lastCapture; // 简单劫规则
    bool m_isBlackTurn = true; // 新增状态：记录当前是否黑子回合
    GameMode m_gameMode = GameMode::Local; // 游戏模式，默认为本地对战
};
